﻿using System.Collections.Generic;
using System.Linq;

namespace Transformable_Engine_v2.Engine.Animation.FrameAnimation
{
    public abstract class FrameAnimationDescription
    {
        protected FrameAnimationDescription()
        {
            AutoStart = true;
        }

        public bool IsLooping { get; set; }

        public bool AutoStart { get; set; }

        public double Delay { get; set; }

        public Dictionary<int, FrameDescription> Frames { get; protected set; }

        private int _currentIndex;

        public FrameDescription CurrentFrame
        {
            get
            {
                return Frames[_currentIndex];
            }
        }

        public double FrameRate
        {
            set
            {
                foreach (var frameDescription in Frames) {
                    frameDescription.Value.Duration = (int) (1000/value);
                }
            }
        }

        public int Duration
        {
            get 
            { 
                return Frames.Sum(x => x.Value.Duration); 
            }
        }

        public int LastFrameId
        {
            set
            {
                Frames[value].IsLastFrame = true;
            }
        }

        public void ChangeFrame()
        {
            _currentIndex = CurrentFrame.NextFrameId;
        }

        public bool IsFinished()
        {
            return CurrentFrame.IsLastFrame && !IsLooping;
        }

        protected void AddFrame(FrameDescription description)
        {
            if(Frames == null) 
            {
                Frames = new Dictionary<int, FrameDescription>();
                _currentIndex = description.Id;
            }

            Frames.Add(description.Id, description);
        }
    }
}